import { Component, OnInit, Input, Output, EventEmitter } from "@angular/core";
import { _HttpClient } from "@delon/theme";
import { LocalStorage } from "@core/local.storage";
import { StatusFollowService } from '@core/statusFollow.service';
import { JzjcMainService } from './jzjc_main.service';
import { TreeTools } from '@core/treeTools.tool';
import { NzMessageService, NzModalService } from 'ng-zorro-antd';
import { JzjcTool } from './jzjc_main.tool';
import { DatePipe } from '@angular/common';
import { environment } from '../../../../../environments/environment';

@Component({
    selector: "app-jzjc-detail",
    templateUrl: "./jzjc_main.detail.html",
    styleUrls: ["./jzjc_main.component.less", "../jzjc.less"],
})
export class JzjcDetailComponent implements OnInit {

    userInfo = JSON.parse(this.ls.get('loginInfo'));
    lockHeadScroll = { y: window.innerHeight - 300 + 'px' };
    detail: any = {
        mode: "",
        zgMode: "",
        data: {},
        footer: [],
        onChangeFxt: () => { },
        onChangeWtdj: () => { },
        onChangeZrbm: () => { },
        tableLoading: false,
        tableData: [],
        zgqk: {},
    }
    pc: any = "";
    bmEditable = true;
    czList: any = [];
    czList_filter: any = [];
    treeNodeStyle = { 'max-height': '300px', 'overflow-y': 'auto', 'overflow-x': 'hidden' };
    stationId = '';
    sblxNodes = [];
    sblxList = [];
    sbmcList = [];

    @Input('detail')
    set inputDetail(info) {
        if (JSON.stringify(info) === '{}') {
            return;
        }
        this.initDetail();
        if (!this.czList.length || info.pc !== this.pc) {
            this.pc = info.pc;
            this.getCz(info.pc);
        }
        this.detail.mode = info.mode || '';
        this.detail.zgMode = info.zgMode || '';

        switch (info.mode) {
            case 'add':
                this.detail.footer[0].label = '新增';
                this.detail.footer[1].show = true;
                break;
            case 'edit': // 全部都可修改
                this.detail.footer[0].show = true;
                this.detail.footer[1].show = true;
                this.detail.footer[0].label = '保存';
                break;
            case 'edit_notBm': // 部门和协助部门不能修改
                this.detail.footer[0].label = '保存';
                this.detail.footer[1].show = false;
                break;
            case 'edit_onlyBm': // 只能修改责任部门
            case 'edit_onlyBms': // 只能修改责任部门和协助部门
                this.detail.footer[0].show = false;
                this.detail.footer[1].show = true;
                break;
            case 'edit_onlyZrr': // 只能修改责任部门和协助部门
                this.detail.footer[0].label = '保存';
                this.detail.footer[0].show = true;
                this.detail.footer[1].show = false;
                break;
            default:
                this.detail.footer[0].show = false;
                this.detail.footer[1].show = false;
                break;
        }

        this.bmEditable = true;
        this.jzjcTool.peopleList = [];
        if (JSON.stringify(info.data) !== '{}') {
            this.setDetailInfo(info.data);
            this.setFxtInfo(info.data.pc);
            this.queryZgqk(info.data.id);
        } else {
            this.detail.data = {};
            this.setFxtInfo(info.pc);
        }

    };

    @Output()
    btnClick = new EventEmitter();

    fxtEditable = false;

    constructor(
        private treeTools: TreeTools,
        public ls: LocalStorage,
        private jzjcMainService: JzjcMainService,
        private statusFollowService: StatusFollowService,
        public jzjcTool: JzjcTool,
        public msg: NzMessageService,
        private datePipe: DatePipe,
        private modalService: NzModalService,
        private http: _HttpClient
    ) { }

    ngOnInit() {

    }

    initDetail() {
        this.detail = {
            mode: 'detail',
            zgMode: 'detail',
            data: {},
            footer: [{
                show: true,
                label: "text", // 按钮文本
                btnType: 'primary',
                onClick: () => {
                    this.btnClick.emit('wait');
                    this.detailOk();
                }
            }, {
                show: true,
                label: "下发", // 按钮文本
                btnType: 'primary',
                onClick: () => {
                    this.btnClick.emit('wait');
                    this.detailOk(true);
                }
            }, {
                show: true,
                btnType: 'default',
                label: "取消", // 按钮文本
                onClick: () => {
                    this.btnClick.emit('close');
                    // this.detailCancel();
                }
            }],
            onChangeFxt: (v) => {
                // this.getGq(v);
                this.getCz(v);
            },
            onChangeWtdj: (v) => {
                this.setZgrq(v);
            },
            onChangeZrbm: (v) => {
                // this.setZgrq(v);
                if (!v) {
                    return;
                }
                this.detail.data.charger = "";
                this.jzjcTool.getPeople(v);
            },
            tableLoading: false,
            tableData: [],
            zgqk: {},
        }
        // 车站再关闭后不会再次请求，这是临时写的处理方法
        this.getCz(window.location.href.split('/')[window.location.href.split('/').length - 1]);
    };

    setFxtInfo(pc) {
        this.detail.data._fxtName = this.jzjcTool.fxtArr[pc];
        this.detail.data.pc = pc;
    }

    getHeight() {
        return window.innerHeight - 350;
    }

    statusFollow(data) {
        return this.statusFollowService.init('jzjc_main_status', data);
    }

    getCz(pc, func?) {
        if (!pc) {
            return;
        }
        this.jzjcMainService.getStationByjcpc(pc).subscribe(res => {
            if (res && res.data && res.data.length) {
                this.czList = res.data[0];
                this.czList_filter = this.czList;
                // this.onChange_cz(this.detail.data.stationname);
            }
            // func && func();
        });
    }
    onChange_cz(v) {
        if (v) {
            this.czList_filter = v ? this.czList.filter(el => el.STATIONNAME.includes(v)) : this.czList;
            for (const item of this.czList_filter) {
                // this.stationId = item.STATIONNAME === v ? item.STATIONID : '';
                if (item.STATIONNAME === v) {
                    this.stationId = item.STATIONID;
                    const url = environment.apiBase + '/csmis/devTypes/getAllTypesByStaId1.jwt?station=' + this.stationId;
                    this.http.get(url).subscribe((res: any) => {
                        this.sblxNodes = this.treeTools.formatTreeNode(res);
                        this.devTypeChange(this.detail.data.devTypeId, 'first');
                    });
                    break;
                }
            }
        } else {
            this.czList_filter = this.czList;
        }
    }

    /**
     * 修改
     * @param params stationid：车站ID，
     * @param params stationname：车站名称，
     * @param params problemtype 问题类型
     * @param params problemtypeid 
     * @param params problemlevel：问题级别（I、II、III），
     * @param params problem：问题内容，
     * @param params chargeorg：责任部门ID，
     * @param params chargeorgname：责任部门名称
     * @param params assistorg 协助部门
     * @param params assistorgname 
     * @param params charger：责任人，
     * @param params rectdate 整改日期
     * @param params note 备注
     * @param params status 
     */
    setDetailInfo(row) {
        this.detail.data = {};
        if (row.chargeorg) {
            this.jzjcTool.getPeople(row.chargeorg);
        }
        if (row.assistorg) {
            row._assistorg = row.assistorg.split(',');
        }
        if (row.rectdate) {
            row._rectdate = new Date(row.rectdate);
        }
        this.detail.data = {
            id: row.id,
            stationid: row.stationid,
            stationname: row.stationname,
            devTypeId: row.devTypeId,
            devName: row.devName,
            devId: row.devId,
            problemtype: row.problemtype,
            problemtypeid: row.problemtypeid,
            problemlevel: row.problemlevel,
            _problemlevelShow: row.problemlevelShow || '',
            problem: row.problem,
            chargeorg: row.chargeorg,
            chargeorgname: row.chargeorgname,
            charger: row.charger,
            note: row.note,
            assistorg: row.assistorg,
            _assistorg: row._assistorg,
            assistorgname: row.assistorgname,
            rectdate: row.rectdate,
            _rectdate: row._rectdate,
            // _fxtName: this.jzjcTool.fxtArr[row.pc]
        }
    }



    detailOk(ifXf?) {
        switch (this.detail.mode) {
            case 'add':
                this.add(ifXf);
                break;
            case 'edit':
            case 'edit_notBm':
            case 'edit_onlyBm':
            case 'edit_onlyBms':
            case 'edit_onlyZrr':
                this.edit(ifXf);
                break;
            default:
                break;
        }
    }

    beforeSave(param) {
        // 此处车站使用的是autocomplete组件，如果绑定ID，则在赋值的时候不会显示中文
        if (param.stationname) {
            // 此处因是根据名称找ID，故keyName和valueName要反着写
            param.stationid = this.treeTools.getTreeNodeName({
                id: param.stationname,
                nodes: this.czList,
                keyName: 'STATIONNAME',
                valueName: 'STATIONID',
            });
        }
        if (param.chargeorg) {
            param.chargeorgname = this.treeTools.getTreeNodeName({
                id: param.chargeorg,
                nodes: this.jzjcTool.bmList,
            });
        }
        if (param._assistorg) {
            const asisArr = param._assistorg.filter(el => el);
            param.assistorg = asisArr.length ? (asisArr.join() + ',') : ""
            param.assistorgname = this.treeTools.getNodeNames({
                ids: param._assistorg,
                nodes: this.jzjcTool.bmList,
            });
        }
        if (param.problemtypeid) {
            param.problemtype = this.treeTools.getTreeNodeName({
                id: param.problemtypeid,
                nodes: this.jzjcTool.wtlxList,
                keyName: 'opValue',
                valueName: 'opName',
            });
        }

        if (param._rectdate) {
            param.rectdate = this.datePipe.transform(param._rectdate, 'yyyy-MM-dd');
        }

        for (const key in param) {
            if (param.hasOwnProperty(key)) {
                const v = param[key];
                if (v === "") {
                    param[key] = " ";
                }
            }
        }
    }



    checkRequired(param, optType?) {
        const reqFields: any = {
            // 'pc': '分析台',
            'stationname': '车站',
            'problemtypeid': '问题类型',
            'problemlevel': '问题等级',
            'problem': '问题内容',
            // '_chargeorg': '责任部门',
            'charger': '责任人',
            '_rectdate': '整改日期',
        }
        for (const key in reqFields) {
            if (reqFields.hasOwnProperty(key)) {
                const fieldName = reqFields[key];
                if (!param[key]) {
                    this.msg.warning(`请填写${fieldName}`);
                    return false;
                }
            }
        }
        return true;
    }


    beforeAdd(param, ifXf?) {
        if (ifXf === true) {
            if (param.chargeorg) {
                param.status = '1';
            } else {
                this.msg.warning('请选择责任部门');
                return false;
            }
        }
        return true;
    }

    add(ifXf?) {
        const check = this.checkRequired(this.detail.data, 'add');
        if (!check) {
            return;
        }
        for (const item of this.sbmcList) {
            if (item.ID === this.detail.data.devId) {
                this.detail.data.devName = item.VC_NAME;
            }
        }
        this.beforeSave(this.detail.data);
        const param = {};
        Object.assign(param, this.detail.data);
        this.beforeSave(param);
        const xfCheck = this.beforeAdd(param, ifXf);
        if (!xfCheck) {
            return;
        }
        this.jzjcTool.removePrivateFields(param);
        this.jzjcMainService.add(param).subscribe(res => {
            if (res && res.msg === 'Ok') {
                this.msg.success('新增成功');
                this.btnClick.emit('close_load');
            } else {
                this.msg.warning('新增失败');
            }
        });
    }


    beforeEdit(param, ifXf?) {
        if (ifXf === true) {
            if (param.chargeorg) {
                if (param.chargeorg === this.userInfo.VC_ORG$ID ||
                    (this.userInfo.VC_ORG$NAME.indexOf('质检组') !== -1 && this.userInfo.VC_PAR$ORG$ID === param.chargeorg)) {
                    this.msg.warning('不能下发给本部门');
                    return false;
                }
                switch (this.userInfo.VC_ORG$ID) {
                    case 'KMBUR_KMNSEG_ORG_40': // 调度
                        param.status = '1';
                        break;
                    case 'KMBUR_KMNSEG_ORG_48': // 电子车间
                        param.status = '11';
                        break;
                    default:
                        if (this.userInfo.N_LEVEL === 30 || this.userInfo.VC_ORG$NAME.indexOf('质检组') !== -1) {
                            param.status = '11';
                        } else {
                            switch (this.userInfo.N_LEVEL) {
                                case 30: // 车间
                                    param.status = '11';
                                    break;
                                default:
                                    break;
                            }
                        }
                        break;
                }

            } else {
                this.msg.warning('请选择责任部门');
                return false;
            }
        }
        return true;
        // if (param.chargeorg !== this.protoData.chargeorg) { // 判断责任部门是否变化
        //     param.status = '1';
        // }
    }

    edit(ifXf?) {
        const check = this.checkRequired(this.detail.data);
        if (!check) {
            return;
        }
        const param = {};
        Object.assign(param, this.detail.data);
        this.beforeSave(param);
        const xfCheck = this.beforeEdit(param, ifXf);
        if (!xfCheck) {
            return;
        }
        this.jzjcTool.removePrivateFields(param);
        this.jzjcTool.removeUnacceptableFields(param);
        this.jzjcMainService.edit(param).subscribe(res => {
            if (res && res.msg === 'Ok') {
                this.msg.success('保存成功');
                this.btnClick.emit('close_load');
            } else {
                this.msg.warning('保存失败');
            }
        });
    }

    markLastOprator(data) {
        let lastOrg = '';
        for (let i = data.length - 1; i >= 0; i--) {
            const row = data[i];
            if (row.orgname === null && row.operator === null) { // 流转状态
                row._editable = false;
            } else {
                if (!lastOrg) {
                    lastOrg = row.org;
                    row._editable = true;
                } else {
                    if (row.org === lastOrg) {
                        row._editable = true;
                    } else {
                        row._editable = false;
                    }
                }
            }
        }
    }

    queryZgqk(problemid) {
        if (!problemid) {
            return;
        }
        this.detail.tableData = [];
        this.detail.tableLoading = true;
        this.jzjcMainService.queryZgqk(problemid).subscribe(res => {
            this.detail.tableLoading = false;
            res.data[0].forEach(row => {
                if (row.content && row.content.indexOf('\\n') !== -1) {
                    row.content = row.content.replace(/\\n/g, '\r\n')
                }
            });
            this.markLastOprator(res.data[0]);
            this.detail.tableData = res.data[0];

            // this.detail.tableData[0].content = '1111\n222'

        })
    }

    addZgqk(type?) {
        if (!this.detail.zgqk.content) {
            this.msg.warning('请填写整改情况');
            return;
        }
        if (type === 'edit' && !this.detail.zgqk.id) {
            this.msg.warning('请双击选中一条记录进行修改');
            return;
        }
        const optName = type === 'add' ? '保存' : '修改';
        this.modalService.confirm({
            nzTitle: `<i>确认</i>`,
            nzWidth: '600',
            nzContent: `确认${optName}吗？`,
            nzOnOk: () => {
                const param: any = {
                    problemid: this.detail.data.id,
                    content: this.detail.zgqk.content,
                }
                if (type === 'edit' && this.detail.zgqk.id) {
                    param.id = this.detail.zgqk.id;
                }
                this.jzjcMainService.addZgqk(param).subscribe(res => {
                    if (res && res.msg === 'Ok') {
                        this.msg.success(optName + '成功');
                        this.queryZgqk(param.problemid);
                        this.detail.zgqk.content = "";
                        this.btnClick.emit('load');
                    } else {
                        this.msg.warning(optName + '失败');
                    }
                });
            }
        });

    }

    setEditInfo(row) {
        // 增加可双击判断逻辑
        if (this.userInfo.VC_ORG$ID === row.org && row._editable === true) {
            this.detail.zgqk = { content: row.content, id: row.id };
        } else {
            this.msg.warning('不能修改此条记录');
            return;
        }
    }


    setZgrq(v) {
        const _date = new Date();
        const todayDate = _date.getDate();
        switch (v) {
            case 'I':
            case '1':
                _date.setDate(todayDate + 2);
                break;
            case 'II':
            case '2':
                _date.setDate(todayDate + 4);
                break;
            case 'III':
            case '3':
                _date.setDate(todayDate + 8);
                break;
            default:
                break;
        }
        this.detail.data._rectdate = _date;
    }
    devTypeChange(e, type) {
        this.sbmcList = [];
        let url = environment.apiBase + '/csmis/publicTree/getDevByStationType.jwt?staid=' + this.stationId + '&typeid=';
        url += e ? e : '';
        this.http.get(url).subscribe((res: any) => {
            if (res.type === "success") {
                if (res.response.data.length) {
                    this.sbmcList = res.response.data;
                }
                if (type !== 'first') {
                    this.detail.data.devId = null;
                }
            }
        });
    }
}
